package com.ehomepay.escrow.transition.common.redis.impl;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.ehomepay.escrow.transition.common.redis.RedisClusterConfigProperties;
import com.ehomepay.escrow.transition.common.redis.RedisService;

/**
 * 
 * @ClassName: RedisServiceImpl 
 * @Description: redis服务实现类 
 * @author shangxuanc
 * @date 2017年8月17日 下午11:01:08
 */
@Service
public class RedisServiceImpl implements RedisService {
    
    @Autowired
    private RedisClusterConfigProperties clusterProperties;
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    /**
     * !!!!!!!!!!!!!!!!加这个前缀很重要
     * 统一增加前缀，需要注意，下面方法调用的key都需要经过这个方法的封装
     * @param key
     * @return
     */
    private String getKeyWithPrekey(String key){
        return clusterProperties.getPrekey() + key;
    }

    @Override
    public String get(String key) {
        String value = stringRedisTemplate.opsForValue().get(getKeyWithPrekey(key));
    	return value == null ? "" : value;
    }
    
    @Override
    public void set(String key, String value) {
        stringRedisTemplate.opsForValue().set(getKeyWithPrekey(key), value);
    }

    @Override
    public void set(String key, String value, int time) {
//        stringRedisTemplate.opsForValue().set(getKeyWithPrekey(key), value, time);
        stringRedisTemplate.opsForValue().set(getKeyWithPrekey(key), value, new Long(time), TimeUnit.SECONDS);
    }

    @Override
    public void delete(String key) {
        stringRedisTemplate.delete(getKeyWithPrekey(key));
    }

	@Override
	public Long incr(String key) {
		return stringRedisTemplate.boundValueOps(getKeyWithPrekey(key)).increment(0);
	}

	@Override
	public void expire(String key, int time) {
		stringRedisTemplate.boundValueOps(getKeyWithPrekey(key)).expire(time, TimeUnit.SECONDS);
	}
	
	@Override
	public Long getExpire(String key) {
		return stringRedisTemplate.getExpire(getKeyWithPrekey(key));
	}
	
	@Override
	public void setList(String key) {}

}
